package com.cx.mall.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.cx.mall.common.util.ResponseEnum;
import com.cx.mall.order.entity.OrderDetail;
import com.cx.mall.order.entity.OrderInfo;
import com.cx.mall.order.model.OrderVO;
import com.cx.mall.order.service.IOrderDetailService;
import com.cx.mall.order.service.IOrderInfoService;
import com.cx.mall.order.service.IOrderService;
import com.cx.mall.proto.Cart;
import com.cx.mall.proto.RequestParam;
import com.cx.mall.proto.ResponseResult;
import com.cx.mall.proto.RpcSimpleGrpc;
import net.devh.boot.grpc.client.inject.GrpcClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements IOrderService {
    @GrpcClient("sku-grpc")
    private RpcSimpleGrpc.RpcSimpleBlockingStub skuStub ;
    @GrpcClient("cart-grpc")
    private RpcSimpleGrpc.RpcSimpleBlockingStub cartStub ;
    @Autowired
    private IOrderInfoService orderInfoService;
    @Autowired
    private IOrderDetailService orderDetailService;
    @Override
    public void save(OrderVO orderVO) throws Exception {
        // 生成订单编号
        String orderId = IdWorker.getIdStr();
        // 分解参数
        List<OrderDetail> orderDetails = orderVO.getOrderDetails();
        List<String> cartIds = orderVO.getCartIds();
        // 1 保存订单详情
        // 1.1 设置各商品的订单编号和合计金额
        List<OrderDetail> details = orderDetails.stream().map(e -> {
            e.setOrderId(orderId);// 设置订单
            // 设置合计金额
            BigDecimal amount = e.getPrice().multiply(new BigDecimal(e.getQuantity()));
            e.setAmount(amount);
            return e;
        }).collect(Collectors.toList());
        // 1.2 保存订单详情
        orderDetailService.saveBatch(details);
        // 2 保存订单
        // 2.1 计算订单总金额
        BigDecimal totalAmount = new BigDecimal(0);
        for (OrderDetail detail : details) {
            totalAmount = totalAmount.add(detail.getAmount());
        }
        // 2.2 创建订单对象
        OrderInfo orderInfo = JSON.parseObject(JSON.toJSONString(orderVO),OrderInfo.class);
        orderInfo.setOrderId(orderId);
        orderInfo.setTotalAmount(totalAmount);
        // 2.3 保存订单
        orderInfoService.save(orderInfo);
        // 3 递减库存
        // 3.1 构建购物车集合
        List<Cart> carts = details.stream().map(e -> {
            Cart cart = Cart.newBuilder()
                    .setSkuId(e.getSkuId())
                    .setNum(e.getQuantity())
                    .build();
            return cart;

        }).collect(Collectors.toList());
        // 3.2 递减库存-远程调用
        RequestParam skuParam = RequestParam.newBuilder().addAllCarts(carts).build();
        ResponseResult result = skuStub.dcount(skuParam);
        if (result.getCode() == 1000) {
            throw new Exception(result.getMessage());
        }
        // 4 删除购物车
        // 4.1 构建购物车集合
        List<Cart> cartList = orderDetails.stream().map(e -> {
            Cart cart = Cart.newBuilder()
                    .setId(e.getId().toString())
                    .build();
            return cart;
        }).collect(Collectors.toList());
        // 4.2 删除购物车-远程调用
        RequestParam cartRequestParam = RequestParam.newBuilder()
                .addAllCarts(cartList)
                .build();
        result = cartStub.deleteCart(cartRequestParam);
        if (result.getCode() == ResponseEnum.FAIL.getCode()){
            throw new Exception(result.getMessage());
        }
    }
}
